package com.caipiao.lottery.lty.handler;

import java.text.Format;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import com.caipiao.lottery.dict.DictAct;
import com.caipiao.lottery.log.TraceLogger;
import jodd.util.StringUtil;
import org.slf4j.Logger;

import jodd.datetime.JDateTime;

import com.caipiao.lottery.config.Config;
import com.caipiao.lottery.core.SYSConstant;
import com.caipiao.lottery.core.SYSInterface;
import com.caipiao.lottery.dbwarpper.PK_Test;
import com.caipiao.util.BizException;
import com.caipiao.util.StringTools;
import com.caipiao.util.db.DBOutCursor;
import com.caipiao.util.db.DBOutString;

public class LtyHandlerHelper
{
	private static final String FORMAT14 = "yyyy-MM-dd HH:mm:ss";
	private static final Format DF14= new SimpleDateFormat(FORMAT14);
	public static String GetTestHandleString(String RemoteIP)
	{
		StringBuffer str_buff = new StringBuffer();

		str_buff.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n");
		str_buff.append("<server>\r\n");

		str_buff.append("<appTime>");
		str_buff.append(DF14.format(new Date()));
		str_buff.append("</appTime>\r\n");


		str_buff.append("<dbTime>");
		DBOutString db_time = new DBOutString("");
		if (PK_Test.Pr_Test(db_time))
		{
			str_buff.append(db_time.toString());
		}
		else
		{
			str_buff.append("DB Test Failed");
		}
		str_buff.append("</dbTime>\r\n");

		str_buff.append("<language>中文</language>\r\n");

		str_buff.append("<remoteIP>");
		str_buff.append(RemoteIP);
		str_buff.append("</remoteIP>\r\n");

		str_buff.append("<lb>");
		str_buff.append(SYSInterface.Instance().App_ID);
		str_buff.append("</lb>\r\n");

		str_buff.append("</server>\r\n");

		return str_buff.toString();
	}

	public static String GetHandicap(String handicap)
	{
		try
		{
			int number = Integer.valueOf(handicap);

			if (number <= 0)
			{
				return String.valueOf(number);
			}
			else if (number > 0)
			{
				return "+" + String.valueOf(number);
			}
		}
		catch(Exception e)
		{
		}

		return handicap;
	}

	public static String GetYptResultLogString(String status, String result, String desc)
	{
		StringBuffer buff = new StringBuffer();

		buff.append(" status:");
		buff.append(status);

		if (null != result && !result.isEmpty())
		{
			buff.append(" result:");
			buff.append(result);
		}

		if (null != desc && !desc.isEmpty())
		{
			buff.append(" desc:");
			buff.append(desc);
		}

		return buff.toString();
	}

	//ErrorCode 映射
	public static String GetErrorCode(String errorCode)
	{
		String errorCode_ = Config.ErrorCode.GetPropValue("ErrorCode." + errorCode);

		if (null == errorCode_ || errorCode_.isEmpty())
		{
			errorCode_ = errorCode;
		}

		return errorCode_;
	}

	//ErrorCode 映射
	public static String GetErrorCode(String errorCode, String SYS)
	{
		String errorCode_ = Config.ErrorCode.GetPropValue("ErrorCode." + errorCode, SYS);

		if (null == errorCode_ || errorCode_.isEmpty())
		{
			errorCode_ = Config.ErrorCode.GetPropValue("ErrorCode." + errorCode);

			if (null == errorCode_ || errorCode_.isEmpty())
			{
				errorCode_ = errorCode;
			}
		}

		return errorCode_;
	}

	//获取错误码描述
	public static String GetErrorCodeDesc(String interFace, String errorCode)
	{
		String Desc = Config.ErrorCode.GetPropValue("ErrorCodeDesc." + errorCode, interFace);

		if (null == Desc || Desc.isEmpty())
		{
			Desc = "ErrorCode:" + errorCode;
		}
		return Desc;
	}

	//数字彩当天开奖时间
	public static String Get_SZC_WinTime_Desc(String endTime, String winTime)
	{
		JDateTime time = new JDateTime(endTime, SYSConstant.JTIME_FORMAT);
		return time.toString("MM-DD ") + winTime;
	}

	//竞彩开奖时间
	public static String Get_JC_WinTime_Desc(String endTime)
	{
		if (endTime.isEmpty())
		{
			return "时间未知";
		}

		JDateTime time = new JDateTime(endTime, SYSConstant.JTIME_FORMAT);

		if (time.getHour() >= 23)	//晚上比赛
		{
			time.addDay(1);	//加一天
			return time.toString("MM-DD ") + "09:00";
		}
		else if (time.getHour() <= 7)	//7点之前
		{
			return time.toString("MM-DD ") + "09:00";
		}

		//延后三个小时
		time.addHour(3);
		return time.toString("MM-DD hh:mm");
	}

	//时间转换
	public static String YptTime2LtyTime(String yptTime)
	{
		if (null == yptTime || yptTime.isEmpty())
		{
			return "";
		}

		JDateTime time = new JDateTime(yptTime, SYSConstant.YPT_JTIME_FORMAT);
		return time.toString(SYSConstant.JTIME_FORMAT);
	}

	public static long GetTimeInMillis(String str14time)
	{
		JDateTime time = new JDateTime(str14time, SYSConstant.JTIME_FORMAT);
		return time.getTimeInMillis();
	}

	//毫秒数转14字节时间
	public static String Get14TimeString(long timeInMillis)
	{
		JDateTime time = new JDateTime(timeInMillis);
		return time.toString(SYSConstant.JTIME_FORMAT);
	}

	//获取一个时间描述
	public static String GetLastTime(String str14time)
	{
		JDateTime exp_time = new JDateTime(str14time, SYSConstant.JTIME_FORMAT);
		return exp_time.toString(" MM-DD hh:mm 前");
	}

	//返回剩余秒数
	public static int GetLeftTime(String str14_now, String str14_expire)
	{
		long expire= (new JDateTime(str14_expire, SYSConstant.JTIME_FORMAT)).getTimeInMillis();
		long now = (new JDateTime(str14_now, SYSConstant.JTIME_FORMAT)).getTimeInMillis();

		if (now > expire)
		{
			return 0;
		}

		return (int) ((expire - now)/1000);
	}

	//返回剩余秒数
	public static int GetLeftTimeFromNow(String str14_expire)
	{
		long now = (new JDateTime()).getTimeInMillis();
		long expire= (new JDateTime(str14_expire, SYSConstant.JTIME_FORMAT)).getTimeInMillis();

		if (now > expire)
		{
			return 0;
		}

		return (int) ((expire - now)/1000);
	}

	public static String GetLeftTimeDesc(String nowTime, String expireTime)
	{
		int leftTime = LtyHandlerHelper.GetLeftTime(nowTime, expireTime);

		return GetLeftTimeDesc(leftTime);
	}

	public static String GetLeftTimeDesc(int leftTimeSec)
	{
		String value = "";
		int count = 0;

		int leftTime = leftTimeSec;

		int days = (int)(leftTime/86400);

		if (days > 0)
		{
			value = days + "天";
			count = 1;
		}

		int left_time = leftTime - days*86400;

		int hours = (int)(left_time/3600);

		left_time = left_time - hours*3600;

		if (hours > 0)
		{
			value = value + hours + "小时";
		}

		if (hours > 0 || count > 0)
		{
			count ++;
		}

		if (count < 2)
		{
			int mins = (int)(left_time/60);
			left_time = left_time - mins*60;

			if (mins > 0)
			{
				value = value + mins + "分";
			}

			if (mins > 0 || count > 0)
			{
				count ++;
			}

			if (count < 2)
			{
				value = value + left_time + "秒";
			}
		}

		return value;
	}

	//返回缓存秒数
	public static int GetLotteryCacheTime(boolean dataEmpty, int timeOutSec, String oExpirTime)
	{
		//计算超时时间
		int timeOut = timeOutSec;

		if (!dataEmpty &&  null != oExpirTime && !oExpirTime.isEmpty())
		{
			int expireSec = LtyHandlerHelper.GetLeftTimeFromNow(oExpirTime);
			if (timeOut > expireSec)
			{
				timeOut = expireSec;
			}
		}
		else if (dataEmpty)
		{
			timeOut = timeOut/10;		//非数据缓存10分之1
		}

		return timeOut;
	}

	//获取订单状态
	public static String GetOrderState(String platForm,
									   String lotteryType,
									   String printStatus,
									   String printErrorCode,
									   String winStatus)
	{
		String head = "ZT@" + platForm + "@";

		String key = head + lotteryType + "@" + printStatus + "@" + printErrorCode + "@" + winStatus;
		String value = Config.StatusMap.GetPropValue("Status." + key);

		if (!value.isEmpty())
		{
			return value;
		}

		key = head  + "@" + printStatus + "@" + printErrorCode + "@" + winStatus;
		value = Config.StatusMap.GetPropValue("Status." + key);

		if (!value.isEmpty())
		{
			return value;
		}

		key = head + lotteryType + "@" + printStatus + "@@" + winStatus;
		value = Config.StatusMap.GetPropValue("Status." + key);

		if (!value.isEmpty())
		{
			return value;
		}

		key = head + "@" + printStatus + "@@" + winStatus;
		value = Config.StatusMap.GetPropValue("Status." + key);

		if (!value.isEmpty())
		{
			return value;
		}

		return head + lotteryType + "@" + printStatus + "@"  + printErrorCode + "@" + winStatus;
	}

	//获取订单状态
	public static String GetIssueState(  String platForm,
										 String lotteryType,
										 String printStatus,
										 String winStatus)
	{
		String head = "QC@" + platForm + "@";

		String key = head + lotteryType + "@" + printStatus + "@" + winStatus;
		String value = Config.StatusMap.GetPropValue("Status." + key);

		if (!value.isEmpty())
		{
			return value;
		}

		key = head + "@" + printStatus + "@" + winStatus;
		value = Config.StatusMap.GetPropValue("Status." + key);

		if (!value.isEmpty())
		{
			return value;
		}

		return head + lotteryType + "@" + printStatus + "@" + winStatus;
	}

	//获取订单状态描述
	public static String GetOrderStateDesc(String lotteryType, String orderState)
	{
		if (!lotteryType.isEmpty())
		{
			String key = lotteryType + "@" + orderState;
			String value = Config.StatusMap.GetPropValue("StatusDesc." + key);
			if (!value.isEmpty())
			{
				return value;
			}
		}

		String value = Config.StatusMap.GetPropValue("StatusDesc." + orderState);

		if (!value.isEmpty())
		{
			return value;
		}
		else
		{
			return "状态异常#状态异常";
		}
	}

	//资金密码
	public static class ActPswData
	{
		public String actPswState = "1";
		public String actPsw = "";
	}


	//输入赔率列表，返回概率列表
	public static void GetRateFromOdd(ArrayList<String> peilv_list, ArrayList<String> gailv_list, int fraction)
	{
		ArrayList<Float> peilv_list_ = new ArrayList<Float>();

		float sum = 0;

		for(String str : peilv_list)
		{
			Float f = Float.valueOf(str);
			peilv_list_.add(f);

			sum += ((f==0)?0:(1/f));
		}

		float pay_back = (sum==0)?0:(1/sum);

		NumberFormat num = NumberFormat.getPercentInstance();
		num.setMaximumIntegerDigits(3);
		num.setMaximumFractionDigits(fraction);

		for(Float f : peilv_list_)
		{
			Float gailv = (f==0)?0:pay_back/f;
			gailv_list.add(num.format(gailv));
		}
	}

	public static String GetTeamZhanJiStr(DBOutCursor oInfo)
	{
		StringBuffer buff = new StringBuffer();

		buff.append(oInfo.getString("sai"));
		buff.append(",");
		buff.append(oInfo.getString("sheng"));
		buff.append(",");
		buff.append(oInfo.getString("ping"));
		buff.append(",");
		buff.append(oInfo.getString("fu"));
		buff.append(",");
		buff.append(oInfo.getString("jin"));
		buff.append(",");
		buff.append(oInfo.getString("shi"));
		buff.append(",");
		buff.append(oInfo.getString("jing"));

		return buff.toString();
	}

	/////////////  红包  ///////////////////
	
	/*
	//读取批次号指定的票列表
	public static String GetBatchTicketList(DBOutCursor oInfo, ArrayList<CouponTicket> couponTicketList)
	{
		String lottery_id = "";
		while(oInfo.next())
		{
			CouponTicket ticket = new CouponTicket();
			
			ticket.ticketId = oInfo.getString("order_id");
			ticket.ticketValue = Long.valueOf(oInfo.getString("order_amount"));
			
			if (lottery_id.isEmpty())
			{
				lottery_id = oInfo.getString("lottery_id");
			}
		}
		
		return lottery_id;
	}
	*/


	//验证优惠券是否可用

	///////////////////

	//检验玩法是否可用
	private static boolean LotteryCanUse(String lotteryId, String couponLottery)
	{
		if (couponLottery.isEmpty())
		{
			return true;
		}

		//玩法分组
		String lotteryGroup = Config.Lottery.GetPropValue("Lottery." + lotteryId + ".Group");

		String[] lottery_list = couponLottery.split(",");

		for (String lottery_str : lottery_list)
		{
			if (null == lottery_str || lottery_str.isEmpty())
			{
				continue;
			}

			//支持所有
			if (lottery_str.equalsIgnoreCase("ALL"))		//支持所有玩法
			{
				return true;
			}

			//玩法
			if (lottery_str.equalsIgnoreCase(lotteryId))		//支持此玩法
			{
				return true;
			}

			//玩法分组
			if (null != lotteryGroup && !lotteryGroup.isEmpty())
			{
				if (lottery_str.equalsIgnoreCase(lotteryGroup))
				{
					return true;
				}
			}
		}

		return false;
	}

	//////////////////////////

	//可用玩法描述
	private static String _GetLotteryDesc(String lottery_list)
	{
		if (lottery_list.isEmpty() || lottery_list.equalsIgnoreCase("ALL"))	//不限制玩法
		{
			return Config.Product.GetPropValue("Coupon.AllUseDesc");
		}
		else
		{
			StringBuffer str_buff = new StringBuffer();

			String[] lottery_list_ = lottery_list.split(",");

			int k=0;
			for (String lottery_id : lottery_list_)
			{
				String lotteryName = Config.Lottery.GetPropValue("LotteryGroup." + lottery_id + ".Name");
				if (null == lotteryName || lotteryName.isEmpty())
				{
					lotteryName = Config.Lottery.GetPropValue("Lottery." + lottery_id + ".Name");
				}

				if (null == lotteryName || lotteryName.isEmpty())
				{
					lotteryName = lottery_id;
				}

				if (k>0)
				{
					str_buff.append(",");
				}

				str_buff.append(lotteryName);

				k++;
			}

			String lotteryDesc = Config.Product.GetPropValue("Coupon.CanUseDesc");
			lotteryDesc = lotteryDesc.replace("{$lottery_list}", str_buff.toString());

			return lotteryDesc;
		}
	}

	//限额描述
	private static String _GetLimitValueDesc(long limitValue)
	{
		if (limitValue <= 0)	//不限制金额
		{
			return Config.Product.GetPropValue("Coupon.NoLimitValueDesc");
		}
		else
		{
			double yuan = StringTools.RMB_Fen2Yuan(limitValue);
			String yuan_ = String.valueOf(yuan);

			String limitValueDesc = Config.Product.GetPropValue("Coupon.LimitValueDesc");
			limitValueDesc = limitValueDesc.replace("{$limitValue}", yuan_);

			return limitValueDesc;
		}
	}

	//红包状态描述
	private static String _GetCouponStatusDesc(String status)
	{
		String statusDesc = Config.Product.GetPropValue("Coupon.Status.Desc." + status);

		if (null == statusDesc || statusDesc.isEmpty())
		{
			statusDesc = status;
		}

		return statusDesc;
	}

	//红包使用时间描述
	private static String _GetCouponUsedDesc(String used_time)
	{
		if (!used_time.isEmpty())
		{
			JDateTime used_date = new JDateTime(used_time, SYSConstant.JTIME_FORMAT);

			String used_date_str = used_date.toString("MM-DD");

			String usedDesc = Config.Product.GetPropValue("Coupon.UsedDesc");
			usedDesc = usedDesc.replace("{$used_date}", used_date_str);

			return usedDesc;
		}

		return "";
	}

	//红包使用时间描述
	private static String _GetCouponExpireDesc(String expire_time)
	{
		if (!expire_time.isEmpty())
		{
			JDateTime expire_date = new JDateTime(expire_time, SYSConstant.JTIME_FORMAT);

			String expire_date_str = expire_date.toString("MM-DD");

			String expireDesc = Config.Product.GetPropValue("Coupon.ExpireDesc");
			expireDesc = expireDesc.replace("{$expire_date}", expire_date_str);

			return expireDesc;
		}

		return "";
	}

	//红包过期时间描述
	private static String _GetCouponValidDesc(String expireDate)
	{
		JDateTime endDate = new JDateTime(expireDate, "YYYYMMDD");

		JDateTime now = new JDateTime();

		int days = now.daysBetween(endDate);

		if (days<=0)	//即将失效
		{
			return Config.Product.GetPropValue("Coupon.ValidDescIm");
		}
		else
		{
			String expireDesc = Config.Product.GetPropValue("Coupon.ValidDesc");
			expireDesc = expireDesc.replace("{$left_day}", String.valueOf(days));

			return expireDesc;
		}
	}
}